﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Flurl;
using Flurl.Http;
using Flurl.Util;
using System.Net.Http;
using System.Collections.Specialized;

namespace Pay.Service {
    public class ArticleService : ServiceBase, IArticleService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        public ArticleService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
        }

        #region 后台管理

        /// <summary>
        /// 获得文章列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<article_dto> GetArticles(ArticleQuery query) {
            var filter = PredicateBuilder.True<Article>();
            filter = filter.And(s => s.Type == query.type);
            var start_time = query.start_time.ToUnix();

            if (!string.IsNullOrEmpty(query.title))
                filter = filter.And(c => c.Title.Contains( query.title));
            if (!string.IsNullOrEmpty(query.mobile)) {
                filter = filter.And(c => c.Merchant.Mobile == query.mobile);
            }
            if (query.merchant_id > 0)
                filter = filter.And(c => c.MerchantId == query.merchant_id);
            if (query.status != ArticleStatus.All)
                filter = filter.And(c => c.Status == query.status);
            if (query.my_id > 0) {
                filter = filter.And(c => c.ReplyArticles.Contains(c.ReplyArticles.FirstOrDefault(r => r.MerchantId == query.my_id && r.Status == ArticleStatus.Normal)));
            }
            if (query.is_highlight.HasValue)
                filter = filter.And(c => c.IsHighLight == query.is_highlight.Value);
            if (query.start_time.HasValue && query.end_time.HasValue) {
                var end_time = query.end_time.Value.AddDays(1).ToUnix();
                filter = filter.And(c => c.CreateTime >= start_time && c.CreateTime <= end_time);
            } else if (query.start_time.HasValue && !query.end_time.HasValue)
                filter = filter.And(c => c.CreateTime >= start_time);
            else if (!query.start_time.HasValue && query.end_time.HasValue) {
                var end_time = query.end_time.Value.AddDays(1).ToUnix();
                filter = filter.And(c => c.CreateTime <= end_time);
            }
            var result = context.Articles.FromCachePaged<Article, article_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(c => c.Sort).ThenByDescending(c => c.CreateTime), query.is_cache ? "Articles" : "");
            return result;
        }
        /// <summary>
        /// 帮助中心推荐文章
        /// </summary>
        /// <returns></returns>
        public List<article_dto> GetRecommendArticles() {
           var result= context.Articles.Where(s => s.IsTop && s.Type == 1).OrderByDescending(s=>s.CreateTime).Take(10).ToList().ToDtoList<article_dto>();
            return result;
        }
        /// <summary>
        /// 获取文章明细
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public article_dto GetArticle(long id) {
            var model = context.Articles.FindById(id);
            return model.ToDtoObject<article_dto>();
        }

        /// <summary>
        /// 添加文章
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public int AddArticle(article_dto dto) {
            if (dto.id == 0) {
                var model = dto.ToDtoObject<Article>();
                model.CreateTime = DateTime.Now.ToUnix();
                model.UpdateTime = DateTime.Now.ToUnix();
                model.Status = ArticleStatus.Normal;
                context.Articles.Add(model);
               
            } else {
                var model = context.Articles.FindById(dto.id);
                model.UpdateTime = DateTime.Now.ToUnix();
                dto.ToDtoObject(model);
            }
            var result = _iUnitOfWork.Commit("Articles");
            return result;
        }

        /// <summary>
        /// 修改文章 状态/置顶/加精
        /// </summary>
        /// <param name="article"></param>
        /// <returns></returns>
        public int UpdateArticle(article_status article) {
            var model = context.Articles.FindById(article.id);
            int count = context.Articles.Max(c => c.Sort);
            if (article.is_top == true) {
                model.IsTop = !model.IsTop;
                if (model.IsTop == false)
                    model.Sort = 0;
                else
                    model.Sort = count + 1;
            } else if (article.is_highlight == true)
                model.IsHighLight = !model.IsHighLight;
            else
                model.Status = article.status;
            model.CreateTime = DateTime.Now.ToUnix();
            return _iUnitOfWork.Commit("Articles");
        }

        /// <summary>
        /// 获取回复帖子分页
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedResult<reply_article_dto> GetReplyArticles(ReplyArticleQuery query) {
            var filter = PredicateBuilder.True<ReplyArticle>();
            filter = filter.And(c => c.Status == ArticleStatus.Normal);
            if (query.article_id > 0)
                filter = filter.And(c => c.ArticleId == query.article_id);
            var result = context.ReplyArticles.FromCachePaged<ReplyArticle, reply_article_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(c => c.CreateTime), query.is_cache ? "ReplyArticle" : "");
            return result;
        }

        /// <summary>
        /// 回复帖子
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public int ReplyArticle(reply_article_dto dto) {
            var article = context.Articles.FindById(dto.article_id);
            article.ReplyNum += 1;
            var model = dto.ToDtoObject<ReplyArticle>();
            model.CreateTime = DateTime.Now.ToUnix();
            model.Status = ArticleStatus.Normal;
            context.ReplyArticles.Add(model);
            var result = _iUnitOfWork.Commit("ReplyArticles", "Articles");
            return result;
        }

        /// <summary>
        /// 删除回复帖子
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int DeleteReplyArticle(long id, long user_id) {
            var model = context.ReplyArticles.FindById(id);
            var article = context.Articles.FindById(model.ArticleId);
            var merchant = context.Merchants.FirstOrDefault(c => c.Id == user_id);
            if (user_id != model.MerchantId && merchant.IsOEM == false)
                throw new ServerErrorException("用户无法删除别人回复帖子");
            model.Status = ArticleStatus.Delete;
            article.ReplyNum -= 1;
            return _iUnitOfWork.Commit("ReplyArticles", "Articles");
        }

        #endregion


        #region app

        /// <summary>
        /// app获取文章
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ApiPagedResult<article_dto_ex> GetArticles(AppArticleQuery query) {
            //var model = context.Articles.ToDtoList<article_dto_ex>();
            var model = GetArticles(new ArticleQuery { page = query.page, size = query.size, merchant_id = query.merchant_id, status = ArticleStatus.Normal, my_id = query.my_id, is_highlight = query.is_highlight == 1 ? true : false, is_cache = true });
            var list = model.rows.ToDtoList<article_dto_ex>();
            var result = new ApiPagedResult<article_dto_ex>(list, model.total_result, model.page, model.size);
            return ApiResultToJson.Json(result);
        }

        /// <summary>
        /// app发布文章
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
		public int Save(article_model dto) {
            int result = 0;
            var model = dto.ToDtoObject<article_dto>();
            result = AddArticle(model);
            return result;
        }

        /// <summary>
        /// app 获取帖子详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public article_dto_ex GetOneArticle(long id) {
            var model = context.Articles.FindById(id);
            model.ClickNum += 1;
            _iUnitOfWork.Commit();
            return model.ToDtoObject<article_dto_ex>();
        }

        /// <summary>
        /// 获取回帖分页列表
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public ApiPagedResult<reply_article_ex> GetReplys(ReplyArticleQuery query) {
            //var model = context.ReplyArticles.ToDtoList<reply_article_ex>();
            query.is_cache = true;
            var model = GetReplyArticles(query);
            var list = model.rows.ToDtoList<reply_article_ex>();
            list.ForEach(c => {
                if (c.merchant_id == query.merchant_id)
                    c.is_delete = true;
            });
            var result = new ApiPagedResult<reply_article_ex>(list, model.total_result, model.page, model.size);
            return ApiResultToJson.Json(result);
        }

        /// <summary>
        /// 回复帖子
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int Save(reply_article_model dto) {
            int result = 0;
            var model = dto.ToDtoObject<reply_article_dto>();
            result = ReplyArticle(model);
            return result;
        }
        #endregion
    }
}
